package com.ruoyi.utils;


import java.math.BigDecimal;

import com.ruoyi.common.annotation.ChangeRecord;
import com.ruoyi.utils.modifiedProperty.ModifiedPropertyInfo;
import com.ruoyi.utils.modifiedProperty.PropertyModelInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 比较对象，并返回值不同的属性
 * @Date: 2021-04-21
 */
public class ModifiedPropertyUtil {
    /**
     * 比较两个对象属性值是否相同
     * 如果不同返回修改过的属性信息
     *
     * @param oldObj
     * @param newObj
     * @param ignoreProperties
     * @param <T>
     * @return 修改过的属性字段
     */
    public static <T> List<ModifiedPropertyInfo> getDifferentProperty(T obj, T oldObj, T newObj, String... ignoreProperties) {
        if (oldObj != null && newObj != null) {
            // 比较全部字段
            if (ignoreProperties == null || ignoreProperties.length > 0) {
                if (oldObj.equals(newObj)) {
                    return Collections.emptyList();
                }
            }
            Map<String, String> propertyNameMap = new HashMap<>();
            Map<String, String> dictTypeMap = new HashMap<>();
            Map<String, Object> sortMap = new HashMap<>();
            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                ChangeRecord annotation = declaredField.getAnnotation(ChangeRecord.class);
                if (null != annotation) {
                    propertyNameMap.put(declaredField.getName(), annotation.propertyName());
                    dictTypeMap.put(declaredField.getName(), annotation.dictType());
                    sortMap.put(declaredField.getName(), annotation.sort());
                }
            }
            List<PropertyModelInfo> oldObjectPropertyValue = getObjectPropertyValue(oldObj, ignoreProperties);
            if (!CollectionUtils.isEmpty(oldObjectPropertyValue)) {
                List<ModifiedPropertyInfo> modifiedPropertyInfos = new ArrayList<>(oldObjectPropertyValue.size());

                List<PropertyModelInfo> newObjectPropertyValue = getObjectPropertyValue(newObj, ignoreProperties);
                Map<String, Object> objectMap = new HashMap<>(newObjectPropertyValue.size());
                // 获取新对象所有属性值
                for (PropertyModelInfo propertyModelInfo : newObjectPropertyValue) {
                    String propertyName = propertyModelInfo.getPropertyName();
                    Object value = propertyModelInfo.getValue();
                    objectMap.put(propertyName, value);
                }

                for (PropertyModelInfo propertyModelInfo : oldObjectPropertyValue) {
                    String propertyName = propertyModelInfo.getPropertyName();
                    Object value = propertyModelInfo.getValue();
                    if (objectMap.containsKey(propertyName)) {

                        Object newValue = objectMap.get(propertyName);
                        ModifiedPropertyInfo modifiedPropertyInfo = new ModifiedPropertyInfo();
                        if (value != null && newValue != null) {
                            if (value instanceof BigDecimal && newValue instanceof BigDecimal) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(value));
                                BigDecimal bigDecimalNewValue = new BigDecimal(String.valueOf(newValue));
                                if (bigDecimalNewValue.compareTo(bigDecimalValue) == 0) {
                                    continue;
                                }
                            }
                            if (!value.equals(newValue)) {
                                modifiedPropertyInfo.setPropertyName(propertyName);
                                modifiedPropertyInfo.setOldValue(typeChange(value));
                                modifiedPropertyInfo.setNewValue(typeChange(newValue));
                                modifiedPropertyInfo.setPropertyExplain(propertyNameMap.get(propertyName));
                                modifiedPropertyInfo.setDictType(dictTypeMap.get(propertyName));
                                modifiedPropertyInfo.setSort((Integer) sortMap.get(propertyName));
                                modifiedPropertyInfos.add(modifiedPropertyInfo);
                            }
                        } else if (value != null && newValue == null) {
                            modifiedPropertyInfo.setPropertyName(propertyName);
                            modifiedPropertyInfo.setOldValue(typeChange(value));
                            modifiedPropertyInfo.setPropertyExplain(propertyNameMap.get(propertyName));
                            modifiedPropertyInfo.setDictType(dictTypeMap.get(propertyName));
                            modifiedPropertyInfo.setSort((Integer) sortMap.get(propertyName));
                            modifiedPropertyInfos.add(modifiedPropertyInfo);
                        } else if (value == null && newValue != null) {
                            modifiedPropertyInfo.setPropertyName(propertyName);
                            modifiedPropertyInfo.setNewValue(typeChange(newValue));
                            modifiedPropertyInfo.setPropertyExplain(propertyNameMap.get(propertyName));
                            modifiedPropertyInfo.setDictType(dictTypeMap.get(propertyName));
                            modifiedPropertyInfo.setSort((Integer) sortMap.get(propertyName));
                            modifiedPropertyInfos.add(modifiedPropertyInfo);
                        }
                    }
                }
                return modifiedPropertyInfos;
            }
        }
        return Collections.emptyList();
    }

    private static String typeChange(Object value) {
        String valueStr = "";
        if (value instanceof Long) {
            valueStr = String.valueOf(value);
        } else if (value instanceof Date) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            valueStr = simpleDateFormat.format(value);
        } else if (value instanceof String) {
            valueStr = String.valueOf(value);
        } else if (value instanceof BigDecimal) {
            valueStr = String.valueOf(value);
        }
        return valueStr;
    }

    /**
     * 通过反射获取对象的属性名称、getter返回值类型、属性值等信息
     *
     * @param obj
     * @param ignoreProperties
     * @param <T>
     * @return
     */
    public static <T> List<PropertyModelInfo> getObjectPropertyValue(T obj, String... ignoreProperties) {
        if (obj != null) {
            Class<?> objClass = obj.getClass();
            PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(objClass);
            List<PropertyModelInfo> modelInfos = new ArrayList<>(propertyDescriptors.length);

            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method readMethod = propertyDescriptor.getReadMethod();
                String name = propertyDescriptor.getName();
                if (readMethod != null && (ignoreList == null || !ignoreList.contains(name))) {
                    Object invoke = null;
                    Class<?> returnType = readMethod.getReturnType();
                    try {
                        invoke = readMethod.invoke(obj);
                        PropertyModelInfo propertyModelInfo = new PropertyModelInfo();
                        propertyModelInfo.setPropertyName(name);
                        propertyModelInfo.setValue(invoke);
                        propertyModelInfo.setReturnType(returnType);
                        modelInfos.add(propertyModelInfo);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        System.out.println("反射获取类【" + objClass.getName() + "】方法异常，");
                    }
                }
            }
            return modelInfos;
        }
        return Collections.emptyList();
    }
}
